package com.sx.micowell.module.web;

import android.annotation.SuppressLint;
import android.net.http.SslError;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.JavascriptInterface;
import android.webkit.SslErrorHandler;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;

import com.example.mvvm.until.LogUtils;
import com.sx.micowell.framework.app.IntentKey;

/**
 * @author: YY
 * @time: 2021/5/29
 * @describe TODO
 */
public class WebViewFragment extends Fragment {

    private WebView mWebView;

    private String url;
    private String content;

    public static WebViewFragment newInstance(String url, String content) {
        WebViewFragment fragment = new WebViewFragment();
        Bundle bundle = new Bundle();
        bundle.putString(IntentKey.KEY, url);
        bundle.putString(IntentKey.DATA, content);
        fragment.setArguments(bundle);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            url = getArguments().getString(IntentKey.KEY);
            content = getArguments().getString(IntentKey.DATA);
        }
    }

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater,
                             @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        mWebView = new WebView(getContext());
        initWebView();
        return mWebView;
    }

    @SuppressLint("SetJavaScriptEnabled")
    private void initWebView() {
        WebSettings webSettings = mWebView.getSettings();
        webSettings.setJavaScriptEnabled(true);
        webSettings.setDomStorageEnabled(true);
        if (!TextUtils.isEmpty(url)) {
            mWebView.loadUrl(url);
        } else {
            loadContent();
        }
        mWebView.addJavascriptInterface(new JavaScriptInterface(), "android");
        mWebView.setWebChromeClient(new WebChromeClient());
        mWebView.setWebViewClient(new WebViewClient() {
            @Override
            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                view.loadUrl(url);
                return true;
            }
            @Override
            public void onReceivedSslError(WebView view, SslErrorHandler handler, SslError error) {
                handler.proceed();
            }

            @Override
            public void onPageFinished(WebView view, String url) {
                super.onPageFinished(view, url);
                view.loadUrl("javascript:" + buildInjection());
            }
        });


    }

    private void loadContent() {
        if (!TextUtils.isEmpty(content)) {
            String data = content.replace("<img",
                    "<img style=\"max-width:100%;width:auto;height:auto;\"");
            mWebView.loadDataWithBaseURL(null, data,
                    "text/html" ,"UTF-8", null);
        }
    }

    private String buildInjection() {
        StringBuilder sb = new StringBuilder();
        sb.append("document.getElementsByTagName('form')[0].onsubmit = function () {");
        sb.append("var applyname, pccc_applyname;var str = '';");
        sb.append("var inputs = document.getElementsByTagName('input');");
        sb.append("for (var i = 0; i < inputs.length; i++) {");
        sb.append("if (inputs[i].name.toLowerCase() === 'applyname') {applyname = inputs[i];}");
        sb.append("else if (inputs[i].name.toLowerCase() === 'pccc_applyname') {pccc_applyname= inputs[i];}");
        sb.append("}");
        sb.append("if (pccc_applyname!= null) {str += pccc_applyname.value;}");
        sb.append("if (applyname!= null) { str += ' , ' + applyname.value;}");
        sb.append("window.JSInterface.processFormInputs(str);");
        sb.append("return true;");
        sb.append("};");
        return sb.toString();
    }

    static class JavaScriptInterface {
        @JavascriptInterface
        public void processFormInputs(String html) {
            LogUtils.e("html-->" + html);
        }
    }


}
